﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Web.Model;
using Portal.Cms.Model;
using Portal.Web.Utility;
using Portal.Cms.Bussiness;
using Portal.Core;
using Portal.Cms.Utility;
using System.Data;
using Portal.Systems.Model;
using Portal.Xml.Utility;
using System.Collections.ObjectModel;

namespace Portal.Cms.Render
{
    public class CategoryPermissionConfigRenderBll
    {
        static void CheckPermission(string SiteId)
        {
            try
            {
                string UserId = WebSessionUtility.GetCurrentLoginUser().UserId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, SystemPermission.StaticId, SystemPermission.funcManage, SystemPermission.funcManage, UserId, true);
            }
            catch (Exception ex)
            {
                string ReturnData = "<div class=CssAccessDenied>" + ex.Message.ToString() + " <span class=CssBack><a href=\"javascript:history.back(-1);\">Quay lại</a></span></div>\r\n";
                throw new Exception(ReturnData);
            }
        }


        static WebFolderCls[] ReadingWebFolders(string SiteId, string Folder)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string XmlFile = WebConfig.GetWebPartLayout(OSiteParam);
            DataSet ds = XmlUtility.GetDataSetFromXmlFile(XmlFile);
            DataView dv = null;
            if (string.IsNullOrEmpty(Folder))
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId=''", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            else
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId='" + Folder + "'", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            WebFolderCls[] WebFolders = WebFolderParser.ParseFromDataView(dv);
            return WebFolders;
        }

        public static bool IsChecked(
            string SiteId,
            string Categories,
            string CategoryId)
        {
            bool Checked = Categories.IndexOf("$" + CategoryId + "$") != -1;
            return Checked;
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                CheckPermission(SiteId);
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                
                string ButtonIconRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                string RoleId = (string)WebEnvironments.Request(SiteId, "RoleId");
                string ActiveDataLanguageId = (string)WebEnvironments.Request(SiteId, "DataLanguageId");
                if (string.IsNullOrEmpty(ActiveDataLanguageId)) ActiveDataLanguageId = "";

                RoleCls ORole = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, RoleId);
                if (ORole == null) throw new Exception("Tham số không hợp lệ!");
                DataLanguageCls[] DataLanguages = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingDataLanguage(SiteId);
                if (string.IsNullOrEmpty(ActiveDataLanguageId) && DataLanguages.Length > 0)
                {
                    ActiveDataLanguageId = DataLanguages[0].DataLanguageId;
                }
                string SelectDataLanguage =
                    "<select id=drpSelectDataLanguage onchange=javascript:ClientOpenConfig('"+RoleId+"');>\r\n";
                for (int iIndex = 0; iIndex < DataLanguages.Length; iIndex++)
                {
                    if (ActiveDataLanguageId.Equals(DataLanguages[iIndex].DataLanguageId))
                    {
                        SelectDataLanguage += "   <option selected value=\"" + DataLanguages[iIndex].DataLanguageId + "\">" + DataLanguages[iIndex].Subject + "</option>\r\n";
                    }
                    else
                    {
                        SelectDataLanguage += "   <option value=\"" + DataLanguages[iIndex].DataLanguageId + "\">" + DataLanguages[iIndex].Subject + "</option>\r\n";
                    }
                }
                SelectDataLanguage += "</select><input type=button class=button value=\"Thực hiện\" onclick=\"javascript:ClientOpenConfig('"+RoleId+"');\">\r\n";

                RoleExtraConfigCls ORoleExtraConfig = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleExtraConfigModel(SiteId, OSiteParam.SiteCode, RoleId, ActiveDataLanguageId);
                string Categories = "";
                if (ORoleExtraConfig != null)
                {
                    Categories = ORoleExtraConfig.Categories;
                }

                string Html =
                    "<script language=javascript>\r\n" +
                    "  function ClientOpenConfig(RoleId)\r\n"+
                    "  {\r\n"+
                    "       DataLanguageId=document.getElementById('drpSelectDataLanguage').value;\r\n"+
                    "       window.open('CategoryPermissionConfig.aspx?RoleId='+RoleId+'&DataLanguageId='+DataLanguageId,'_self');\r\n"+
                    "  }\r\n"+
                        
                    "  function ProcessExpandCollapse(Id)\r\n" +
                    "  {\r\n" +
                    "     if(document.getElementById(Id).className=='Collapsed')\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Expanded';\r\n" +
                    "     }\r\n" +
                    "     else\r\n" +
                    "     {\r\n" +
                    "         document.getElementById(Id).className='Collapsed';\r\n" +
                    "     }\r\n" +
                    "  }\r\n" +
                   
                   "    function ProcessCheckCategory(Id)\r\n" +
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        checked=document.getElementById('chk'+Id).checked;\r\n" +
                   "        CheckedIds=document.getElementById('txtCheckedCategory').value;\r\n" +
                   "        CheckedIds = Portal.Cms.Render.CategoryPermissionConfigRenderBll.ServerSideProcessCheckCategory(SiteId,CheckedIds,Id,checked).value;\r\n" +
                   "        document.getElementById('txtCheckedCategory').value=CheckedIds;\r\n" +
                   "    }\r\n" +

                    "   function Save(RoleId)\r\n" +
                    "   {\r\n" +
                    "       SiteId='" + SiteId + "';\r\n" +
                    "       DataLangageId=document.getElementById('drpSelectDataLanguage').value;\r\n" +
                    "       CheckIds=document.getElementById('txtCheckedCategory').value;\r\n" +
                    "       OAjaxOut = Portal.Cms.Render.CategoryPermissionConfigRenderBll.ServerSideSaveCheck(SiteId,  RoleId, DataLangageId, CheckIds).value;\r\n" +
                    "       if(OAjaxOut.Error)\r\n" +
                    "       {\r\n" +
                    "           alert(OAjaxOut.InfoMessage);\r\n" +
                    "           return;\r\n" +
                    "       }\r\n" +
                    "       alert(OAjaxOut.InfoMessage);\r\n" +
                    "   }\r\n" +
                    " </script>\r\n" +
                    " <input type=hidden type=textbox id=\"txtCheckedCategory\" value=\"" + Categories + "\"/>\r\n" +
                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:Save('" + RoleId + "');\"><img class=image src=\"" + ButtonIconRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                    "            <li onclick=\"javascript:window.open('CategoryPermission.aspx','_self');\"><img class=image src=\"" + ButtonIconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    " </div>\r\n" +
                    "<h3>Phân quyền chuyên mục - " + ORole.RoleName + "</h3>\r\n" +
                    "<div class=CssFunction>Chọn phạm vi thiết lập: "+SelectDataLanguage+"</div>\r\n"+
                    "<div class=TreeHolder>\r\n" +
                            BuildCategory(SiteId,RoleId,Categories, ActiveDataLanguageId, "TreeView").HtmlContent +
                    "</div>\r\n";


                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut BuildCategory(
            string SiteId, 
            string RoleId,
            string Categories,
            string ActiveDataLanguageId, 
            string TreeViewId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                DataLanguageCls ODataLanguage = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateDataLanguageModel(SiteId, ActiveDataLanguageId);

                //string XmlFile = OSiteParam.PathRoot + "\\admin\\xmldata\\news\\category\\"+ODataLanguage.DataLanguage+"\\Category.xml";
                //DataSet ds = new DataSet();
                //ds.ReadXml(XmlFile);
                //DataView dv = new DataView(ds.Tables[0], "ParentId='0'", "", DataViewRowState.CurrentRows);

                GroupDataCategoryCls[] GroupDataCategories = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).ReadingGroupDataCategory(SiteId, ActiveDataLanguageId);

             
                string Html =
                    "<div class=CssListField>\r\n" +
                    "<ul id=\"" + TreeViewId + "\" class=\"TreeView\">\r\n";
                for (int iIndex = 0; iIndex < GroupDataCategories.Length; iIndex++)
                {
                    string Id = GroupDataCategories[iIndex].GroupDataCategoryId;
                    string Name = GroupDataCategories[iIndex].Name;
                    //DataView dvSub = new DataView(ds.Tables[0], "ParentId='" + Id + "'", "", DataViewRowState.CurrentRows);
                    if (GroupDataCategories[iIndex].SubGroupDataCategories.Count>0)
                    {
                        Html += " <li id=\"" + Id + "\" class=\"Expanded\">\r\n" +
                                    "<a href=\"javascript:ProcessExpandCollapse('" + Id + "');\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span></a>\r\n" +
                                        "<input type=hidden value=\"0\" id=\"txtReadSubField" + Id + "\"><ul id=\"ulSubField" + Id + "\">\r\n" +
                                            ServerSideReadingSubField(SiteId,GroupDataCategories[iIndex].SubGroupDataCategories, ActiveDataLanguageId, Categories, Id).HtmlContent +
                                        "</ul>\r\n" +
                                    "</li>\r\n";
                    }
                    else
                    {
                        bool Checked = IsChecked(SiteId, Categories, Id);
                        Html += 
                                " <li id=\"" + Id + "\" class=\"Collapsed\">\r\n" +
                                "<input " + (Checked ? "CHECKED" : "") + " type=checkbox class=checkbox onchange=\"javascript:ProcessCheckCategory('" + Id + "','')\" id=\"chk" + Id + "\" style=\"margin-right:4px;\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span>\r\n" +
                                "<input type=hidden value=\"0\" id=\"txtReadSubField" + Id + "\"><ul id=\"ulSubField" + Id + "\">\r\n" +
                                        "</ul>\r\n" +
                                    "</li>\r\n";
                    }
                }
                Html += "</ul>\r\n" +
                      "</div>\r\n";
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideReadingSubField(
            string SiteId, 
            Collection<GroupDataCategoryCls> SubGroupDataCategories,
            string DataLanguageId,
            string Categories,
            string CategoryId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                DataLanguageCls ODataLanguage = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateDataLanguageModel(SiteId, DataLanguageId);
                //string XmlFile = OSiteParam.PathRoot + "\\admin\\xmldata\\news\\category\\" + ODataLanguage.DataLanguage + "\\Category.xml";

                ////string XmlFile = OSiteParam.PathRoot + "\\admin\\xmldata\\news\\Portal_vi_Category.xml";
                //DataSet ds = new DataSet();
                //ds.ReadXml(XmlFile);
                //DataView dv = new DataView(ds.Tables[0], "ParentId='" + CategoryId + "'", "", DataViewRowState.CurrentRows);

                string Html = "";
                for (int jIndex = 0; jIndex < SubGroupDataCategories.Count; jIndex++)
                {
                    string Id = SubGroupDataCategories[jIndex].GroupDataCategoryId;
                    string Name = SubGroupDataCategories[jIndex].Name;
                    bool Checked = IsChecked(SiteId, Categories, Id);
                    Html += " <li class=liSubTreeViewItem>\r\n" +
                            "       <input " + (Checked?"CHECKED":"")+ " type=checkbox class=checkbox onchange=\"javascript:ProcessCheckCategory('" + Id + "','')\" id=\"chk" + Id + "\" style=\"margin-right:4px;\"><span id=\"spanMainFieldName" + Id + "\">" + Name + "</span>\r\n" +
                            " </li>\r\n";
                }
                OAjaxOut.RetNumber = SubGroupDataCategories.Count;
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public string ServerSideProcessCheckCategory(string SiteId, string CheckedIds, string Id, bool Checked)
        {
            if (Checked)
            {
                if (!string.IsNullOrEmpty(CheckedIds))
                {
                    CheckedIds = CheckedIds + ";";
                }
                CheckedIds = CheckedIds + "$"+Id+"$";
            }
            else
            {
                CheckedIds = CheckedIds.Replace("$"+Id+"$", "");
            }
            CheckedIds = CheckedIds.Replace(";;", ";");
            if (CheckedIds.Length > 0)
            {
                if (CheckedIds[0].ToString().Equals(";"))
                {
                    CheckedIds = CheckedIds.Substring(1);
                }
            }
            return CheckedIds;
        }

        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideSaveCheck(
            string SiteId, 
            string RoleId, 
            string DataLanguageId,
            string CheckIds)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
                RoleExtraConfigCls ORoleExtraConfig = new RoleExtraConfigCls();
                ORoleExtraConfig.AssetCode = AssetCode;
                ORoleExtraConfig.Categories = CheckIds;
                ORoleExtraConfig.DataLanguageId = DataLanguageId;
                ORoleExtraConfig.RoleExtraConfigId = System.Guid.NewGuid().ToString();
                ORoleExtraConfig.RoleId = RoleId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).SaveRoleExtraConfig(SiteId, RoleId, DataLanguageId, ORoleExtraConfig);
                OAjaxOut.InfoMessage = "Cập nhật thành công chức năng phân quyền truy cập cho chuyên mục";
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}
